package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.config.FileServerConfig;
import io.renren.constant.AppConstant;
import io.renren.entity.BmInfoEntity;
import io.renren.service.OnlineStudyService;
import io.renren.util.Base64Utils;
import io.renren.util.DfsUtil;
import io.renren.util.ImageMergeUtil;
import io.renren.vo.FileServerResponse;
import io.renren.vo.RespModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ThinkPad on 2018/11/12.
 */
@RestController
@RequestMapping("/onlinestudy")
@Api(tags = "在线学习接口")
public class OnlineStudyController {

    private Logger logger = LoggerFactory.getLogger(OnlineStudyController.class);

    @Autowired
    private OnlineStudyService onlineStudyService;

    @Autowired
    private FileServerConfig fileServerConfig;

    @PostMapping(value = "/whetherSubscribe/{userId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "判断学员是否预约学习", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<Map<String, Object>> whetherSubscribe(@PathVariable String userId) {
        /*****1、查询是否报名学习*****/
        Map<String, Object> xybmInfo = onlineStudyService.queryXybmInfo(userId);
        /*****2、查询用户预约信息*****/
        Integer subscribeAmount = onlineStudyService.querySubscribeInfo(userId);
        Map<String, Object> result_map = new HashMap<>();
        /*****3、学员是否预约*****/
        boolean wetherSubscibe = false;
        if (subscribeAmount > 0) {
            wetherSubscibe = true;
        }

        if (CollectionUtils.isEmpty(xybmInfo)) {
            /*****4、无学员信息*****/
            result_map.put("sfxw", "");
            result_map.put("shzt", "");
            result_map.put("bmlx", "");
        }
        result_map.put("isSubscribe", wetherSubscibe);
        return new RespModel<>("SUCCESS", "000", "", result_map);
    }


    @PostMapping(value = "/getSubscribeDateList/{studytype}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取学习预约时间列表", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<List<Map<String, Object>>> getSubscribeDateList(@PathVariable String studytype, String address) {
        LocalDate now = LocalDate.now();
        List<Map<String, Object>> result_maps = onlineStudyService.querySubscribeDateList(now.toString(), studytype, address);
        return new RespModel<>(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", result_maps);
    }

    @PostMapping(value = "/checkCreditscore/{userid}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "检查用户积分是否满足线上报名条件", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<Map> checkCreditscore(@PathVariable String userid) {
        Map<String, Object> map = onlineStudyService.queryCreditscore(userid);
        Map<String, Object> result_map = new HashMap<>();
        if (CollectionUtils.isEmpty(map) || (Integer) map.get("creditscore") < 80) {
            result_map.put("satisfy", "no");
            result_map.put("message", "信誉积分不足，请到车管所预约报名！");
        } else {
            result_map.put("satisfy", "yes");
            result_map.put("message", "信誉积分满足条件");
        }

        return new RespModel<>(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", result_map);
    }

    @PostMapping(value = "/checkWetherSignUp/{userid}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询用户是否线下报过名", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<Map> checkWetherSignUp(@PathVariable String userid) {
        Map<String, Object> map = onlineStudyService.queryBmxx(userid);
        Map<String, Object> map1 = onlineStudyService.queryXybmInfo(userid);
        Map result_map = new HashMap();
        if (CollectionUtils.isEmpty(map1)) {
            result_map.put("shzt", -1);
        } else {
            result_map.put("shzt", map1.get("shzt"));
        }
        if (!CollectionUtils.isEmpty(map)) {
            result_map.put("sfbgm", "1");
            result_map.put("msg", "该学员已报名学习中！");
        } else {
            result_map.put("sfbgm", "0");
            result_map.put("msg", "该学员未报过名！");
        }

        return new RespModel<>(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", result_map);
    }

    @Login
    @PostMapping(value = "/signUpStudy/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存用户报名信息", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<String> signUpStudy(@Validated BmInfoEntity bminfo, HttpServletRequest request) {
        Map result_map = new HashMap();
        String userid = ((String) request.getAttribute("username"));
        Map<String, Object> bmxx = onlineStudyService.queryBmxx(userid);
        if (!CollectionUtils.isEmpty(bmxx)) {
            result_map.put("msg", "该学员已报名学习中！");
        } else {
            bminfo.setSfxw("0");
            bminfo.setShzt("0");
            bminfo.setLdate(new Date());
        }
        try {
            onlineStudyService.saveBmInfo(bminfo);
        } catch (Exception e) {
            return new RespModel<>(AppConstant.SYSTEM_IS_EXCEPTION.getName(),
                    AppConstant.SYSTEM_IS_EXCEPTION.getValue(),
                    e.getMessage(),
                    "");
        }
        return new RespModel<>(AppConstant.STATU_SUCCESS.getName(),
                AppConstant.STATU_SUCCESS.getValue(),
                "",
                "");
    }

    @Login
    @PostMapping(value = "/getXyxx/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询学员信息", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel<Map> getXyxx(HttpServletRequest request) {
        String userid = ((String) request.getAttribute("username"));
        Map<String, Object> xybmInfo = onlineStudyService.queryXybmInfo(userid);
        if (CollectionUtils.isEmpty(xybmInfo)) {
            return new RespModel<>(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", null);
        } else {
            Integer xx_time = onlineStudyService.queryDryxSfxw(String.valueOf(xybmInfo.get("xy_id")));
            String sfxw = "0";
            if (xybmInfo.get("bmlx").equals("0")) {
                if (xx_time != null && 240 == xx_time) {
                    sfxw = "1";
                }
            } else if (xybmInfo.get("bmlx").equals("1")) {
                if (xx_time != null && 180 == xx_time) {
                    sfxw = "1";
                }
            } else {
                return new RespModel<>(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", null);
            }

            /***********修改是否学完状态**************/
            if (sfxw.equals("1")) {
                HashMap<String, String> paramMap = new HashMap<>();
                paramMap.put("xy_id", String.valueOf(xybmInfo.get("xy_id")));
                paramMap.put("sfxw", sfxw);
                onlineStudyService.updateSfxw(paramMap);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("xy_id", String.valueOf(xybmInfo.get("xy_id")));
            map.put("xxdate", LocalDate.now().toString());
            Integer learningTime = onlineStudyService.queryXxjlLearningTime(map);
            xybmInfo.put("todayjf", learningTime);
            xybmInfo.put("sfxw", sfxw);
        }

        return new RespModel<>(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", xybmInfo);
    }


    @PostMapping(value = "/getStudyAddress", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取学习地点", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getStudyAddress() {
        List<Map<String, String>> studyAddress = onlineStudyService.queryStudyAddress();
        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", studyAddress);
    }

    @PostMapping(value = "/updateAvatar/{xy_id}")
    @ApiOperation(value = "更新驾驶员头像")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel updateAvatar(@PathVariable Integer xy_id, MultipartFile img) {
        try {
            if (null == img || img.isEmpty()) {
                return new RespModel(AppConstant.PARAM_IS_MISS.getName(), AppConstant.PARAM_IS_MISS.getValue(), "", null);
            }
            FileServerResponse fileServerResponse = DfsUtil.uploadFileByMultipartFile(img, fileServerConfig.getImageUploadUrl());
            Map paramMap = new HashMap();
            paramMap.put("xy_id", xy_id);
            paramMap.put("avatar", fileServerResponse.getRealHttpUrl());

            onlineStudyService.updateAvatar(paramMap);
        } catch (IOException e) {
            e.printStackTrace();
            return new RespModel<>(AppConstant.STATU_FAIL.getName(), AppConstant.STATU_FAIL.getValue(), e.getMessage(), null);
        }

        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", null);
    }

    @PostMapping(value = "/getXxjl/{xy_id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取学员学习记录", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK", response = RespModel.class),
            @ApiResponse(code = 500, message = "服务端异常", response = RespModel.class)})
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getXxjl(@PathVariable Integer xy_id) {
        List<Map> maps = onlineStudyService.queryXxjlById(String.valueOf(xy_id));
        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", maps);
    }

    @PostMapping("/getVideoList")
    @ApiOperation(value = "查询学习视频")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getVideoList() {
        List<Map> maps = onlineStudyService.queryVideoList();
        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", maps);
    }

    @PostMapping("/stuImg/{xy_id}")
    @ApiOperation(value = "上传学习图片")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel stuImg(@PathVariable Integer xy_id, String videoImage, String photoImage,String video_id) {
        byte[] bytes = Base64Utils.GenerateImageFromBase64(videoImage);
        byte[] bytes1 = Base64Utils.GenerateImageFromBase64(photoImage);
        if (bytes == null || bytes1 == null) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺失图片！", null);
        }

        byte[] merge = ImageMergeUtil.merge(bytes, bytes1);
        FileServerResponse fileServerResponse = DfsUtil.uploadFileByBinary(xy_id + "-studyImage.png", merge, ContentType.IMAGE_PNG, fileServerConfig.getImageUploadUrl());
        Map paramMap = new HashMap();
        paramMap.put("xy_id", String.valueOf(xy_id));
        paramMap.put("img", fileServerResponse.getRealHttpUrl());
        paramMap.put("xxdate", LocalDate.now().toString());
        paramMap.put("video_id",video_id);
        onlineStudyService.saveStudyImg(paramMap);
        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", null);
    }

    @PostMapping(value = "/getXxjlImage/{xy_id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value="获取学习视频截图",produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getXxjlImage(@PathVariable String xy_id,String video_id){
        if(StringUtils.isEmpty(video_id)){
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS,"缺失视频标识",null);
        }
       List<Map> resultList = onlineStudyService.queryXxjlImage(xy_id,video_id);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS,"",resultList);
    }

    @PostMapping("/stuTime/{xy_id}")
    @ApiOperation(value = "更新学习时长")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel stuTime(@PathVariable Integer xy_id, @RequestParam String bmlx) {
        Map paramMap = new HashMap();
        paramMap.put("xy_id", String.valueOf(xy_id));
        paramMap.put("xxdate", LocalDate.now().toString());
        paramMap.put("bmlx", bmlx);
        onlineStudyService.updateDryx(paramMap);
        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", null);
    }

    @PostMapping("/getExam/{userid}")
    @ApiOperation(value = "获取考试题目")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getExam(@PathVariable String userid, @RequestParam String type) {
        Map paramMap = new HashMap();
        paramMap.put("score", 0);
        paramMap.put("userid", userid);
        try {
            List<Map<String, Object>> maps = onlineStudyService.saveExamPaper(paramMap, "1");
            paramMap.put("questionList", maps);
            return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new RespModel(AppConstant.STATU_FAIL.getName(), AppConstant.STATU_FAIL.getValue(), e.getMessage(), null);
        }
    }

    @PostMapping(value = "/calcScore/{userid}/{examdId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "计算试题分数", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel calcScore(@PathVariable String userid, @PathVariable String examdId, @RequestParam String quesList) {
        Map<String, Object> map = onlineStudyService.calcScore(userid, examdId, quesList);
        return new RespModel(AppConstant.STATU_SUCCESS.getName(), AppConstant.STATU_SUCCESS.getValue(), "", map);
    }

    @PostMapping(value = "/ksxx/{xy_id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "生成学习计划", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel ksxx(@PathVariable String xy_id, @RequestParam String bmlx) {
        Map paramMap = new HashMap();
        paramMap.put("xy_id", xy_id);
        paramMap.put("bmlx", bmlx);
        return onlineStudyService.ksxx(paramMap);
    }
}
